package com.example.utils;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.example.common.CommonResult;
import com.example.constant.Constants;
import com.example.pufang.pojo.Admin;
import com.example.pufang.pojo.User;
import com.example.pufang.service.UserService;
import com.example.pufang.vo.LoginUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;


@Component
public class TokenUtil {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserService userService;


    // 在redis中通过缓存获取移动端用户手机号码
    public String getFrontUserPhone(HttpServletRequest request) {

        String token = request.getHeader(Constants.HEADER_AUTHORIZATION_KEY);

        Object phone = redisUtil.get(Constants.HEAD_FRONT_TOKEN + token);

        return String.valueOf(phone);
    }


    // 移动端用户登录，在redis中保存token
    public String createFrontUserToken(LoginUserVo user) {

        String token = new PufangUtils().getUuid();
        redisUtil.set(Constants.HEAD_FRONT_TOKEN + token, user.getPhone(), 86400L);

        return token;
    }

    // admin用户退出登录，删除redis中存储的token
    public Boolean deleteFrontUserToken(HttpServletRequest request) {

        String token = request.getHeader(Constants.HEADER_AUTHORIZATION_KEY);

        if (!StringUtils.hasText(token)) {
            return false;
        }

        redisUtil.del(Constants.HEAD_FRONT_TOKEN + token);

        return true;
    }

    // 在redis中通过缓存获取管理员用户id
    public Integer getAdminId(HttpServletRequest request) {

        String token = request.getHeader(Constants.HEADER_AUTHORIZATION_KEY);

        Object id = redisUtil.get(Constants.HEAD_ADMIN_TOKEN + token);

        return (Integer) id;
    }

    // admin用户登录，在redis中保存token
    public String createAdminToken(Admin admin) {

        String token = new PufangUtils().getUuid();
        redisUtil.set(Constants.HEAD_ADMIN_TOKEN + token, admin.getId(), 86400L);

        return token;
    }

    // admin用户退出登录，删除redis中存储的token
    public Boolean deleteAdminToken(HttpServletRequest request) {

        String token = request.getHeader(Constants.HEADER_AUTHORIZATION_KEY);

        if (!StringUtils.hasText(token)) {
            return false;
        }

        redisUtil.del(Constants.HEAD_ADMIN_TOKEN + token);

        return true;
    }

}
